package com.qf.filter;

import com.qf.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 29125
 * @version V1.0
 * @Project java2203
 * @Package com.qf.filter
 * @Description:鉴权过滤器,判断消费者用户   loginUser   /login.jsp
 * @Date 2022/5/23 10:08
 */
@WebFilter("/*")
public class PermFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取用户的访问路径
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        //获取到用户访问路径并在控制台打印输出
        String uriStr = request.getRequestURI();
        System.out.println("===uriStr==="+uriStr);

        //判断用户路径，放行所有静态资源，用户登录·路径·，用户注册，首页，商品查询等路径
        //判断路径的扩展名，是js就放行，  js和jsp文件使用contains无法判断
        if (uriStr.lastIndexOf(".")>0){
            String extStr = uriStr.substring(uriStr.lastIndexOf("."));//得到路径名 .后的内容
            if (extStr!=null){//.后的内容不为空，存在扩展名
                if (".js".equals(extStr)){
                    //扩展名（存在并且）与.js相等，放行
                    filterChain.doFilter(servletRequest,servletResponse);
                    return;
                }
            }
        }

        if (uriStr.contains("/login")||uriStr.contains("/code")||uriStr.contains("/user")||uriStr.contains("register")
            ||uriStr.contains("/admin/login")||uriStr.contains(".css")||uriStr.contains("admin")//消费者放行
            ||uriStr.contains(".jpg")||uriStr.contains(".png")||uriStr.contains("/type")//商品类型查看放行
            ||uriStr.contains(".gif")||uriStr.contains(".eot")||uriStr.contains("/goods")//商品放行
            ||uriStr.contains(".svg")||uriStr.contains(".ttf")||uriStr.contains("/index")//消费者首页放行
            ||uriStr.contains(".woff")||uriStr.contains(".woff2"))   {
            //访问路径包含首页，页面，图片等等路径，可以放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //获取session对象
        HttpSession session = request.getSession();
        //从session中获取用户对象
//        User user = (User)session.getAttribute("admin");
        User user = (User)session.getAttribute("loginUser");
        if (user!=null){
            //用户存在放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            //用户不存在,返回重定向到登录页面
//            response.sendRedirect("/admin/login.jsp");
            response.sendRedirect("/login.jsp");
        }


    }

    @Override
    public void destroy() {

    }
}
